package com.dmgis.qxfw.dataservice.commonservice.dmgis_mongodb_srv.controller;

import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/dataservice")
public class MongoRequestController {

    MongoService1 ms = new MongoService1();

    @RequestMapping("/select")
    @ResponseBody
    public Object selectData(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        byte[] result = null;
        String collectionName = "";
        //获取参数名 返回一个枚举类型
        Enumeration<String> em = request.getParameterNames();
        Map<String, Object> queryMap = Maps.newHashMap();
        //遍历
        while (em.hasMoreElements()) {
            String name = (String) em.nextElement();
            String value = request.getParameter(name);
            if ("collectionName".equals(name)) {
                collectionName = value;
            }
            //添加到集合中
            queryMap.put(name, value);

        }
        if (StringUtils.isBlank(collectionName)) {
            return "collectionName参数不能为空，请确定数据库表名称";
        }
        try {
            result = ms.selectData(queryMap);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return result;
    }

    @RequestMapping("/insert")
    @ResponseBody
    public Object insertData(HttpServletRequest request, HttpServletResponse response) {
        int result = 0;
        int count = 0;
        String collectionName = "";
        Enumeration<String> em = request.getParameterNames();
        Map<String, Object> insertMap = Maps.newHashMap();
        while (em.hasMoreElements()) {
            String name = (String) em.nextElement();
            String value = request.getParameter(name);
            if ("collectionName".equals(name)) {
                collectionName = value;
            }
            //条件添加到集合中
            insertMap.put(name, value);
        }
        if (StringUtils.isBlank(collectionName)) {
            return "collectionName参数不能为空，请确定数据库表名称";
        }
        try {
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            if (request instanceof MultipartHttpServletRequest) {
                // 将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multiRequest.getFileNames();
                if (multipartResolver.isMultipart(request) && iter.hasNext()) {
                    // 获取multiRequest 中所有的文件名
                    while (iter.hasNext()) {
                        // 一次遍历所有文件
                        MultipartFile file = multiRequest.getFile(iter.next().toString());
                        if (file != null) {
                            // insertMap.put("fileName", file.getName());
                            insertMap.put("data", file.getBytes());
                            int flag = ms.insertData(insertMap);
                            result += flag;
                            count++;
                            // files.add(file);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return String.format("总共插入了%d个文件，成功了%d个文件", result, count);
    }

    @RequestMapping("/update")
    @ResponseBody
    public Object updateData(HttpServletRequest request, HttpServletResponse response) {
        long count = 0;
        Enumeration<String> em = request.getParameterNames();
        String collectionName = "";
        Map<String, Object> updateMap = Maps.newHashMap();
        Map<String, Object> updateData = Maps.newHashMap();
        while (em.hasMoreElements()) {
            String name = (String) em.nextElement();
            String value = request.getParameter(name);
            if ("collectionName".equals(name)) {
                collectionName = value;
            }
            updateMap.put(name, value);

        }
        if (StringUtils.isBlank(collectionName)) {
            return "collectionName参数不能为空，请确定数据库表名称";
        }
        try {
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            if (request instanceof MultipartHttpServletRequest) {
                // 将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multiRequest.getFileNames();
                if (multipartResolver.isMultipart(request) && iter.hasNext()) {
                    // 获取multiRequest 中所有的文件名
                    while (iter.hasNext()) {
                        // 一次遍历所有文件
                        MultipartFile file = multiRequest.getFile(iter.next().toString());
                        if (file != null) {
                            updateData.put("data", file.getBytes());
                            count = ms.updateData(updateMap, updateData);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        String result = "";
        if (count == -1) {
            result = "更新失败";
        } else {
            result = String.format("成功更新了%d个文件", count);
        }
        return result;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object deleteData(HttpServletRequest request, HttpServletResponse response) {
        long count = 0;
        Enumeration<String> em = request.getParameterNames();
        Map<String, Object> deleteMap = Maps.newHashMap();
        String collectionName = "";
        while (em.hasMoreElements()) {
            String name = (String) em.nextElement();
            String value = request.getParameter(name);
            if ("collectionName".equals(name)) {
                collectionName = value;
            }
            deleteMap.put(name, value);

        }
        if (StringUtils.isBlank(collectionName)) {
            return "collectionName参数不能为空，请确定数据库表名称";
        }
        try {
            count = ms.deleteData(deleteMap);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        String result = "";
        if (count == -1) {
            result = "删除失败";
        } else {
            result = String.format("成功删除了%d个文件", count);
        }
        return result;
    }


}
